﻿#ifndef ITEMEDITOR_H
#define ITEMEDITOR_H

#include <common/baseeditor.h>

class ItemEditor : public BaseEditor
{
public:
    explicit ItemEditor(QWidget *parent = Q_NULLPTR)
        : BaseEditor(parent)
    {
        itemModel = nullptr;
        form = WF_NORMAL;
    }

    virtual QString getCategoryByIndex(const QModelIndex &index) const
    {
        QString category;
        if(form == WF_NORMAL)
        {
            QModelIndex p_index=index.parent();
            if(p_index == QModelIndex())
                category=index.data().toString();
            else
                category=p_index.data().toString();
        }
        else
            category=index.sibling(index.row(),0).data().toString();

        return category;
    }

    virtual bool getItemByIndex(const QModelIndex &index)
    {
        if(!category.isEmpty())
            category.clear();
        if(!label.isEmpty())
            label.clear();

        if(form == WF_NORMAL)
        {
            QModelIndex p_index=index.parent();
            if(p_index != QModelIndex())
            {
                category=p_index.data().toString();
                label=index.data().toString();
                return true;
            }
            else
                return false;
        }
        else
        {
            category=index.sibling(index.row(),0).data().toString();
            label=index.sibling(index.row(),1).data().toString();
            return true;
        }
    }

    virtual bool getDetail()
    {
        if(!detail.isEmpty())
            detail.clear();

        QSqlQuery query;
        QString sql=QString("select detail from %1 where category='%2' AND label ='%3'")
                .arg(table)
                .arg(category)
                .arg(label);
        query.exec(sql);
        if(query.next())
        {
            detail = query.value(0).toString();
            return true;
        }
        else
            return false;
    }


    virtual QList<QStandardItem *> getLabelItems(const QString &category) const
    {
        QList<QStandardItem *> items;
        QSqlQuery query;
        query.exec(QString("select label from %1 where category = '%2'")
                   .arg(table)
                   .arg(category));
        while(query.next())
        {
            QString label=query.value("label").toString();
            items.append(new QStandardItem(label));
        }

        return items;
    }

protected:
    WorkForm form;
    QStandardItemModel *itemModel;
    QString category;
    QString label;
    QString detail;
}

#endif // ITEMEDITOR_H
